import { defineStore } from 'pinia'
import { ref } from 'vue'
import DCYX_STUDY_API, {
  TodayTimeRecord,
  TodayVocabReport,
} from '@/api/dcyx/study.api'

import type { DailyTimeRecord } from '@/api/dcyx/daily-tIme-records.api'
import DAILY_TIME_RECORDS_API from '@/api/dcyx/daily-tIme-records.api'
import DCYX_PROGRAM_API from '@/api/dcyx/program.api'
import type { ProgramItem } from '@/api/dcyx/program.api'
import { store } from '@/store'
import { useDcyxSeriesStore } from '@/store'

export const useDcyxStudyStore = defineStore('dcyx_study', () => {
  const dcyxSeriesStore = useDcyxSeriesStore()

  const todayReport = ref<DailyTimeRecord>({
    onlineTime: '00:00:00',
    effectiveTime: '00:00:00',
    efficiency: '0',
    id: '0',
    userId: '0',
    recordDate: '0',
    onlineSeconds: 0,
    effectiveSeconds: 0,
  } as DailyTimeRecord)

  let timer: number | undefined
  let syncTimer: number | undefined
  let lastSyncSeconds = ref(0)
  let currentSeconds = ref(0)

  const todayVocabReport = ref<TodayVocabReport | null>(null)

  const startOnlineTimeTracking = async () => {
    try {
      const res = await DAILY_TIME_RECORDS_API.getTodayOnlineSeconds()
      currentSeconds.value = Number(res.onlineSeconds ?? 0)
      lastSyncSeconds.value = Number(res.onlineSeconds ?? 0)
      // console.log('startOnlineTimeTracking res', res)
      // todayReport.value = res
      // time2 保留 todayReport.value.time2 保留自己时间的 时分秒
      todayReport.value.onlineTime = res.onlineTime.split(' ')[1]
      todayReport.value.effectiveTime = res.effectiveTime.split(' ')[1]
      // console.log('todayReport.value.time1', todayReport.value.time1)
      // console.log('todayReport.value.time2', todayReport.value.time2)
      // console.log('todayReport.value', todayReport.value)
      todayReport.value.efficiency = res.efficiency

      // 每秒本地自增
      timer = window.setInterval(() => {
        currentSeconds.value++
        todayReport.value.onlineTime = formatSeconds(currentSeconds.value)
      }, 1000)

      // 每60秒同步一次到后端
      syncTimer = window.setInterval(async () => {
        const delta = currentSeconds.value - lastSyncSeconds.value
        if (delta > 0) {
          await DAILY_TIME_RECORDS_API.addOnlineOrEffectiveSeconds({
            onlineSeconds: delta,
            effectiveSeconds: 0,
          })
          lastSyncSeconds.value = currentSeconds.value
        }
      }, 60000)
    } catch (error) {
      console.error('获取今日在线时长失败', error)
    }
  }

  const stopOnlineTimeTracking = () => {
    if (timer) clearInterval(timer)
    if (syncTimer) clearInterval(syncTimer)
    // 离开前做最后一次同步
    const delta = currentSeconds.value - lastSyncSeconds.value
    if (delta > 0)
      DAILY_TIME_RECORDS_API.addOnlineOrEffectiveSeconds({
        onlineSeconds: delta,
        effectiveSeconds: 0,
      })
  }

  const formatSeconds = (seconds: number) => {
    const hours = Math.floor(seconds / 3600)
    const minutes = Math.floor((seconds % 3600) / 60)
    const remainingSeconds = seconds % 60
    return `${pad(hours)}:${pad(minutes)}:${pad(remainingSeconds)}`
  }

  const pad = (num: number) => num.toString().padStart(2, '0')

  // const fetchTodayReport = () => {
  //   return new Promise<DailyTimeRecord>((resolve, reject) => {
  //     DAILY_TIME_RECORDS_API.getTodayOnlineSeconds()
  //       .then((res: DailyTimeRecord) => {
  //         console.log('res', res)
  //         todayReport.value = res
  //         resolve(res)
  //       })
  //       .catch((error: any) => {
  //         reject(error)
  //       })
  //   })
  // }

  // const fetchCurrentProgram = () => {
  //   return new Promise((resolve, reject) => {
  //     DCYX_PROGRAM_API.getCurrentUserProgram()
  //       .then((res) => {
  //         currentProgram.value = res
  //         dcyxSeriesStore.currentSeriesParentId = Number(res.parentSeriesId)
  //         dcyxSeriesStore.currentSeriesId = Number(res.seriesId)
  //         resolve(res)
  //       })
  //       .catch((error) => {
  //         reject(error)
  //       })
  //   })
  // }

  // getProgramBySeriesId
  const fetchProgramBySeriesId = () => {
    return new Promise((resolve, reject) => {
      DCYX_PROGRAM_API.getProgramBySeriesId({
        pageNum: 1,
        pageSize: 50,
        seriesId: String(dcyxSeriesStore.currentSeriesId),
      })
        .then((res) => {
          resolve(res)
        })
        .catch((error) => {
          reject(error)
        })
    })
  }

  const fetchTodayVocabReport = async () => {
    try {
      const res = await DCYX_STUDY_API.getTodayVocabReport()
      todayVocabReport.value = res
      return res
    } catch (error) {
      console.error('获取今日单词学习报告失败', error)
      todayVocabReport.value = null
      throw error
    }
  }

  return {
    todayReport,
    todayVocabReport,
    fetchTodayVocabReport,
    // currentProgram,
    // fetchTodayReport,
    // fetchCurrentProgram,
    fetchProgramBySeriesId,
    startOnlineTimeTracking,
    stopOnlineTimeTracking,
  }
})

export function useDcyxStudyStoreHook() {
  return useDcyxStudyStore(store)
}
